package com.example.movie.ui.home

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.movie.R
import com.example.movie.common.model.vm.CommonViewModel
import com.example.movie.common.service.LocationService
import com.example.movie.ui.home.adapter.BaseFragmentPagerAdapter
import com.example.movie.ui.home.tabs.RecommendFragment
import com.example.movie.ui.home.tabs.TopFragment
import com.example.movie.ui.user.search.SearchActivity
import com.example.movie.utils.ToastUtil
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.tab.QMUITab
import com.qmuiteam.qmui.widget.tab.QMUITabSegment
import com.zaaach.citypicker.CityPicker
import com.zaaach.citypicker.adapter.OnPickListener
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.model.HotCity
import com.zaaach.citypicker.model.LocateState
import kotlinx.android.synthetic.main.fragment_home.*


class HomeFragment : Fragment() {

    private val commonViewModel: CommonViewModel by activityViewModels()

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setLocationObserver()
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    private fun setLocationObserver() {
        commonViewModel.locatedCity.observe(viewLifecycleOwner, {
            it?.let {
                CityPicker.from(this@HomeFragment).locateComplete(it, LocateState.SUCCESS)
            }

        })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initTabBars()
        initViewEvent()
        initTabFragments()
    }

    private fun initTabFragments() {
        val fragments = mutableListOf<Fragment>()
        val recommend = RecommendFragment()
        val top = TopFragment()

        fragments.add(recommend)
        fragments.add(top)

        //设置viewpaper适配器,这里有个坑，适配器传childFragmentManager，否则返回来viewPaper内容丢失
        viewPaper.adapter = BaseFragmentPagerAdapter(childFragmentManager, fragments)
        viewPaper.offscreenPageLimit = 15
        //为tabSegment设置viewPaper
        qmui_tab_segment.setupWithViewPager(viewPaper, false)
        //调整自适应
        qmui_tab_segment.mode = QMUITabSegment.MODE_SCROLLABLE
        //设置选项卡间距
        val space = QMUIDisplayHelper.dp2px(context, 16);
        qmui_tab_segment.setItemSpaceInScrollMode(space)
        qmui_tab_segment.setPadding(space, 0, space, 0)
        qmui_tab_segment.notifyDataChanged()
    }

    private fun initViewEvent() {
        searchView.setOnClickListener {
          startActivity(Intent(requireActivity(),SearchActivity::class.java))
        }

        //城市选择监听
        city.setOnClickListener {
            //申请定位权限
            XXPermissions
                .with(requireContext())
                .permission(Permission.Group.LOCATION)
                .request(object : OnPermission {
                    override fun hasPermission(granted: MutableList<String>?, all: Boolean) {
                        if (all) {
                            LocationService.startLocation(requireContext(), commonViewModel)
                        } else {
                            LocationService.startLocation(requireContext(), commonViewModel)
                            ToastUtil.toast(
                                requireContext(),
                                "如需后台定位还需自行去设置定位权限!"
                            )
                        }
                    }

                    override fun noPermission(denied: MutableList<String>?, never: Boolean) {
                        if (never) {
                            ToastUtil.toast(requireContext(), "被拒绝授权，请主动申请授权定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(requireActivity(), denied);
                        } else {
                            ToastUtil.toast(requireContext(), "因没有定位权限所以无法定位您所在的城市!");
                        }
                    }
                })
            openCityPicker()
        }
        flag.setOnClickListener {
            openCityPicker()
            LocationService.startLocation(requireContext(), commonViewModel)
        }
    }

    private fun initTabBars() {
        val tabs = mutableListOf<QMUITab>(
            QMUITabSegment(context)
                .tabBuilder()
                .setText("推荐")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("榜单")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("预告片")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("精彩片段")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("资讯")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("娱乐圈")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("科幻")
                .build(context),
            QMUITabSegment(context)
                .tabBuilder()
                .setText("爱情")
                .build(context)
        )
        //添加选项卡
        tabs.forEach {
            qmui_tab_segment.addTab(it)
        }
    }

    private fun openCityPicker() {
        val hotCities: MutableList<HotCity> = mutableListOf(
            HotCity("北京", "北京", "101010100"),
            HotCity("上海", "上海", "101020100"),
            HotCity("广州", "广东", "101280101"),
            HotCity("深圳", "广东", "101280601"),
            HotCity("杭州", "浙江", "101210101")
        )
        CityPicker.from(this)
            .enableAnimation(true)
            .setAnimationStyle(0)
            .setLocatedCity(null)
            .setHotCities(hotCities)
            .setOnPickListener(object : OnPickListener {
                override fun onPick(position: Int, data: City) {
                    Toast.makeText(requireContext(), data.name, Toast.LENGTH_SHORT).show()
                    city.text = data.name
                    commonViewModel.selectedCity.value =
                        City(data.name, data.province, data.pinyin, data.code)
                }

                override fun onCancel() {
                    LocationService.stopLocation()
                }

                override fun onLocate() {

                }
            })
            .show()
    }

    /**
     * 页面销毁时销毁相关服务对象
     */
    override fun onDestroy() {
        super.onDestroy()
        LocationService.destroyLocation()
    }


}

